package com.example.demo.leetcode;

/**
 * 链接： https://leetcode.cn/problems/merge-two-sorted-lists/description/
 * @author WangYX
 * @date 2024/01/30 14:09
 * @version 1.0.0
 */
public class _21_合并两个有序链表 {

    public static void main(String[] args) {
        ListNode list1 = new ListNode(1, new ListNode(2, new ListNode(4)));
        ListNode list2 = new ListNode(1, new ListNode(3, new ListNode(4)));
        ListNode listNode = mergeTwoLists(list1, list2);
        System.out.println(listNode);
    }

    public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode listNode = new ListNode();
        merge(listNode, list1, list2);
        return listNode.next;
    }


    public static void merge(ListNode listNode, ListNode list1, ListNode list2) {
        if (list1 == null && list2 != null) {
            listNode.next = list2;
        } else if (list2 == null && list1 != null) {
            listNode.next = list1;
        } else if (list1 != null && list2 != null) {
            if (list1.val <= list2.val) {
                listNode.next = new ListNode(list1.val);
                merge(listNode.next, list1.next, list2);
            } else {
                listNode.next = new ListNode(list2.val);
                merge(listNode.next, list1, list2.next);
            }
        }
    }
}
